import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_plus/flutter_swiper_plus.dart';
import 'package:get/get.dart';
import 'package:namewava/pages/calendar/widgets/jc_calendar_bottom_title.dart';
import 'package:namewava/pages/calendar/widgets/jc_calendar_head.dart';
import 'package:namewava/pages/calendar/widgets/jc_calendar_title.dart';
import 'package:namewava/pages/calendar/widgets/jc_calendar_write.dart';
import 'package:namewava/utils/jc_cache.dart';
import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_screenutil_info.dart';
import 'package:namewava/utils/jc_text_style.dart';
import 'package:namewava/utils/js_request.dart';
import 'package:notification_centre/notification_centre.dart';
import 'package:flutter_card_swiper/flutter_card_swiper.dart';

class JcCalendar extends StatefulWidget {
  const JcCalendar({super.key});

  @override
  State<JcCalendar> createState() => _JcCalendarState();
}

class _JcCalendarState extends State<JcCalendar>
    with AutomaticKeepAliveClientMixin {
  RxString userAvater = ''.obs;
  List nameRcords = [];
  bool isFinshed = false;
  int index = 0;
  Map months = {
    '01': 'January',
    '02': 'February',
    '03': 'March',
    '04': 'April',
    '05': 'May',
    '06': 'June',
    '07': 'July',
    '08': 'August',
    '09': 'September',
    '10': 'October',
    '11': 'November',
    '12': 'December'
  };
  RxBool _isFirstRegister = false.obs;
  List haveRecordDate = [];
  _wavaUserInfo() {
    JsRequest.getWavaUserInfo(success: (res) {
      userAvater.value = res['avatarThumbUrl'];
    });
  }

  _getFirstRegister() {
    var isFirstRegister = JcCache.getInstance().get('isFirstRegister');
    if (isFirstRegister is bool && isFirstRegister) {
      _isFirstRegister.value = true;
    } else {
      _isFirstRegister.value = false;
    }
  }

  _getMyWavaName({String time = ''}) {
    ///获取本地所有的记录
    var wavaNameRecord = JcCache.getInstance().get('wavaNameRecord');
    var wavaUserId = JcCache.getInstance().get('wavaUserId');
    haveRecordDate = [];
    List tmp = [];
    if (wavaNameRecord == null) {
      tmp = [];
    } else {
      wavaNameRecord = jsonDecode(wavaNameRecord);
      for (var element in wavaNameRecord) {
        var userId = element['userId'];
        var recordTime = element['time'];
        if (wavaUserId == userId) {
          if (!haveRecordDate.contains(recordTime)) {
            haveRecordDate.add(recordTime);
          }
        }
        if (time != '' && time == recordTime) {
          if (wavaUserId == userId) {
            ///当前用户 指定日期的
            tmp.add(element);
          }
        }

        if (time == '' && wavaUserId == userId) {
          ///当前用户 的
          tmp.add(element);
        }
      }
    }

    nameRcords = tmp;
    if (nameRcords.isNotEmpty) {
      int max = nameRcords.length;
      while (max < 5) {
        nameRcords.add({'wavaName': '', 'time': ''});
        max++;
      }
    }
    // nameRcords = [];
    isFinshed = true;
    index = 0;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    print('JcCalendar-initState');
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getFirstRegister();
      _wavaUserInfo();

      _getMyWavaName();
    });
    NotificationCenter().addObserver('wavaLoninEvents', this, (r) {
      if (mounted) {
        _getFirstRegister();
        _wavaUserInfo();
        _getMyWavaName();
      }
    });

    NotificationCenter().addObserver('wavaRecordChange', this, (r) {
      if (mounted) {
        _getMyWavaName();
      }
    });
    NotificationCenter().addObserver('wavaFixUserAvatar', this, (r) {
      if (mounted) {
        _isFirstRegister.value = false;
        userAvater.value = r['url'];
        // _wavaUserInfo();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    NotificationCenter().removeObserver('wavaLoninEvents', this);
    NotificationCenter().removeObserver('wavaRecordChange', this);
    NotificationCenter().removeObserver('wavaFixUserAvatar', this);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      height: JcScreenutilInfo.screenHeight,
      width: JcScreenutilInfo.screenWidth,
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage(JcImagePath.jcMineBg), fit: BoxFit.fill)),
      child: Column(
        children: [
          Obx(() {
            return JcCalendarHead(
              userUrl: userAvater.value,
              record: haveRecordDate,
              isFirstRegister: _isFirstRegister.value,
              sureTap: (time) {
                print(time);
                _getMyWavaName(time: time);
              },
            );
          }),
          // SizedBox(
          //   height: 100.h,
          // ),
          // Image.asset(JcImagePath.jcWavaBwlTitle),
          const JcCalendarTitle(),
          Expanded(
              child: SingleChildScrollView(
            child: Column(
              children: [
                isFinshed
                    ? _wavaContent()
                    : const SizedBox(
                        height: 0,
                      ),
                nameRcords.isNotEmpty
                    ? _wavaNameWidget()
                    : SizedBox(
                        height: 10.h,
                      ),
                nameRcords.isNotEmpty
                    ? _timeWidget()
                    : SizedBox(
                        height: 10.h,
                      ),
                const JcCalendarBottomTitle(),
                JcCalendarWrite(
                  top: 10.h,
                )
              ],
            ),
          ))
        ],
      ),
    );
  }

  _wavaNameWidget() {
    String wavaName = nameRcords[index]['wavaName'];
    return wavaName != ''
        ? Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                wavaName,
                style: JcTextStyle.sourceKeynoteartHansTextStyle(
                    18.sp, const Color(0xFF0836A6)),
              ),
              SizedBox(
                width: 5.w,
              ),
              // Container(
              //   height: 20.h,
              //   width: 30.w,
              //   color: Colors.red,
              // ),
              InkWell(
                child: Image.asset(
                  JcImagePath.jcWavaRecordCopy,
                  height: 12.h,
                  width: 27.w,
                  fit: BoxFit.fill,
                ),
                onTap: () {
                  Clipboard.setData(ClipboardData(text: wavaName));
                  EasyLoading.showSuccess('Success');
                },
              ),
            ],
          )
        : const SizedBox(
            height: 0,
          );
  }

  _wavaContent() {
    return nameRcords.isNotEmpty
        ? Container(
            // color: Colors.red,
            margin: EdgeInsets.only(bottom: 20.h),
            width: double.infinity,
            height: 240.h,
            child: Swiper(
                layout: SwiperLayout.DEFAULT,
                viewportFraction: 0.5,
                scale: 0.3,
                // customLayoutOption:
                //     CustomLayoutOption(startIndex: -1, stateCount: 3)
                //         // .addRotate([-45.0 / 180, 0.0, 45.0 / 180])
                //         .addTranslate([
                //   /// 左-当前-右卡片的偏移量
                //   Offset(-190.w, 30.h),
                //   const Offset(0.0, 0.0),
                //   Offset(190.w, 30.h),
                // ]),
                index: index,
                itemWidth: double.infinity,
                itemHeight: 240.h,
                // itemHeight: 231.h,
                itemBuilder: (context, index) {
                  String wavaName = nameRcords[index]['wavaName'];
                  return wavaName != ''
                      ? SizedBox(
                          width: 200.w,
                          height: 240.h,
                          child: Image.asset(JcImagePath.jcWavaBwlItemBg),
                        )
                      : Stack(
                          children: [
                            SizedBox(
                              width: 200.w,
                              height: 240.h,
                              child: Image.asset(JcImagePath.jcWavaBwlEmpty),
                            ),
                            Positioned(
                                bottom: 15.h,
                                right: 0,
                                left: 0,
                                child: Container(
                                  alignment: Alignment.center,
                                  child: Text(
                                    'Nothing',
                                    style:
                                        JcTextStyle.poetsenOneRegularTextStyle(
                                            18.sp, Colors.white),
                                  ),
                                ))
                          ],
                        );
                },
                onIndexChanged: (indenx) {
                  print(index);
                  index = indenx;
                  setState(() {});
                },
                itemCount: nameRcords.length),
          )
        : SizedBox(
            height: 240.h,
            width: double.infinity,
            // color: Colors.red,
            //  alignment: Alignment.center,
            child: Swiper(
                layout: SwiperLayout.DEFAULT,
                viewportFraction: 0.5,
                scale: 0.3,
                // customLayoutOption:
                //     CustomLayoutOption(startIndex: -1, stateCount: 3)
                //         // .addRotate([-45.0 / 180, 0.0, 45.0 / 180])
                //         .addTranslate([
                //   /// 左-当前-右卡片的偏移量
                //   Offset(-190.w, 30.h),
                //   const Offset(0.0, 0.0),
                //   Offset(190.w, 0.h),
                // ]),
                index: index,
                itemWidth: 200.w,
                itemHeight: 240.h,
                // itemHeight: 231.h,
                itemBuilder: (context, indenx) {
                  return Stack(
                    children: [
                      SizedBox(
                        width: 200.w,
                        height: 240.h,
                        child: Image.asset(JcImagePath.jcWavaBwlEmpty),
                      ),
                      Positioned(
                          bottom: 15.h,
                          right: 0,
                          left: 0,
                          child: Container(
                            alignment: Alignment.center,
                            child: Text(
                              'Nothing',
                              style: JcTextStyle.poetsenOneRegularTextStyle(
                                  18.sp, Colors.white),
                            ),
                          ))
                    ],
                  );
                },
                onIndexChanged: (indenx) {
                  print(index);
                  index = indenx;
                },
                itemCount: 3),
          );
  }

  // _wavaContent() {
  //   return nameRcords.isNotEmpty
  //       ? Container(
  //           // color: Colors.red,
  //           margin: EdgeInsets.only(bottom: 20.h),
  //           width: double.infinity,
  //           height: 240.h,
  //           child: CardSwiper(
  //               //  controller: controller,
  //               cardsCount: nameRcords.length,
  //               maxAngle: 90,
  //               scale: 1,
  //               onSwipe: _onSwipe1,
  //               onUndo: _onUndo,
  //               numberOfCardsDisplayed: 3,
  //               backCardOffset: const Offset(40, 15),
  //               padding: EdgeInsets.zero,
  //               cardBuilder: (
  //                 context,
  //                 index,
  //                 horizontalThresholdPercentage,
  //                 verticalThresholdPercentage,
  //               ) {
  //                 return Row(
  //                   mainAxisAlignment: MainAxisAlignment.center,
  //                   children: [
  //                     //  SizedBox(width: 0.5*(JcScreenutilInfo.screenWidth - 200.w),),
  //                     SizedBox(
  //                       width: 200.w,
  //                       height: 240.h,
  //                       child: Image.asset(JcImagePath.jcWavaBwlItemBg),
  //                     )
  //                   ],
  //                 );
  //               }))
  //       : SizedBox(
  //           height: 240.h,
  //           width: double.infinity,
  //           // color: Colors.red,
  //           //  alignment: Alignment.center,
  //           child: CardSwiper(
  //               //  controller: controller,
  //               cardsCount: 3,
  //               maxAngle: 90,
  //               scale: 1,
  //               onSwipe: _onSwipe,
  //               onUndo: _onUndo,
  //               numberOfCardsDisplayed: 3,
  //               backCardOffset: const Offset(40, 15),
  //               padding: EdgeInsets.zero,
  //               cardBuilder: (
  //                 context,
  //                 index,
  //                 horizontalThresholdPercentage,
  //                 verticalThresholdPercentage,
  //               ) {
  //                 return Row(
  //                   mainAxisAlignment: MainAxisAlignment.center,
  //                   children: [
  //                     //  SizedBox(width: 0.5*(JcScreenutilInfo.screenWidth - 200.w),),
  //                     Stack(
  //                       children: [
  //                         SizedBox(
  //                           width: 200.w,
  //                           height: 240.h,
  //                           child: Image.asset(JcImagePath.jcWavaBwlEmpty),
  //                         ),
  //                         Positioned(
  //                             bottom: 15.h,
  //                             right: 0,
  //                             left: 0,
  //                             child: Container(
  //                               alignment: Alignment.center,
  //                               child: Text(
  //                                 'Nothing',
  //                                 style: JcTextStyle.poetsenOneRegularTextStyle(
  //                                     18.sp, Colors.white),
  //                               ),
  //                             ))
  //                       ],
  //                     )
  //                   ],
  //                 );
  //               }));
  // }

  bool _onSwipe1(
    int previousIndex,
    int? currentIndex,
    CardSwiperDirection direction,
  ) {
    // debugPrint(
    //   'The card $previousIndex was swiped to the ${direction.name}. Now the card $currentIndex is on top',
    // );
    debugPrint(
      'The card $currentIndex ',
    );
    index = currentIndex ?? 0;
    setState(() {});
    return true;
  }

  bool _onSwipe(
    int previousIndex,
    int? currentIndex,
    CardSwiperDirection direction,
  ) {
    // debugPrint(
    //   'The card $previousIndex was swiped to the ${direction.name}. Now the card $currentIndex is on top',
    // );
    debugPrint(
      'The card $previousIndex ',
    );
    return true;
  }

  bool _onUndo(
    int? previousIndex,
    int currentIndex,
    CardSwiperDirection direction,
  ) {
    debugPrint(
      'The card $currentIndex was undod from the ${direction.name}',
    );
    return true;
  }

  _timeWidget() {
    String time = nameRcords[index]['time'];
    if (time != '') {
      List timeArray = time.split('-');
      return Container(
        margin: EdgeInsets.only(top: 10.h),
        child: Text(
          '${timeArray[2]} ${months[timeArray[1]]} ${timeArray[0]}',
          style: JcTextStyle.sourceKeynoteartHansTextStyle(
              10.sp, const Color(0xFF747474)),
        ),
      );
    } else {
      return const SizedBox(
        height: 0,
      );
    }
  }

  _getTime(String t) {}

  @override
  bool get wantKeepAlive => true;
}
